

const { ipcRenderer } = require('electron');
const moment = require('moment');
const fixWebmMetaInfo  = require('fix-webm-metainfo');
const fixWebmDuration = require("fix-webm-duration");

//https://zhuanlan.zhihu.com/p/601642188
//https://juejin.cn/post/7272523490498215991
//https://segmentfault.com/q/1010000019685388
//https://blog.csdn.net/qq_36958916/article/details/108529705
//https://blog.csdn.net/qq_36958916/article/details/108529705
/*
MediaUtils.getUserMedia(true, true, function (err, stream) {
        if (err) {
            throw err;
            alert("请检查摄像头!", function () { });
        } else {
            // 通过 MediaRecorder 记录获取到的媒体流
            var options = {
                audioBitsPerSecond: 128000,
                videoBitsPerSecond: 2500000,
                mimeType: "video/webm;codecs=vp8,opus"//webm类型一定要加codecs=vp8,opus，否则会导致录制时候时而可以用时而不能用
            }
            mediaRecorder = new MediaRecorder(stream, options);
            mediaStream = stream;
            var chunks = [];//通道
            video.srcObject = stream;
            video.play();
            videosContainer.appendChild(video);
            mediaRecorder.ondataavailable = function (e) {
                mediaRecorder.blobs.push(e.data);
                chunks.push(e.data);
            };
            mediaRecorder.blobs = [];
            mediaRecorder.onstop = function (e) {
            var duration = new Date().getTime() - startTime;//停止录制时候 用当前时间减去开始录制的时间
                //console.log(new Date().getTime())
                //console.log(duration)
                var tmpBlob = new Blob(chunks, { 'type': mediaRecorder.mimeType });
                //调用设置时长代码。该函数基于fix-webm-duration.js
                ysFixWebmDuration(tmpBlob, duration, function (fixedBlob) {
                    recorderFile = fixedBlob
                   //console.log(recorderFile)
                });
                chunks.length = 0;
                if (null != stopRecordCallback) {
                    stopRecordCallback();
                }
                $('#openCamera').text('保存');
            };
            $('#openCamera').text('开始录制');
        }
    });
*/

let micEnable = false;
let webmMimeType = "";

ipcRenderer.on('SET_AUDIO', async (event, ENABLE) => {
  micEnable = ENABLE;
  if (micEnable) {
    webmMimeType = 'video/webm; codecs=vp9,opus';
  } else {
    webmMimeType = 'video/webm; codecs=vp9';
  }
});

ipcRenderer.on('SET_SOURCE', async (event, sourceId) => {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({
      audio: micEnable,
      video: {
        mandatory: {
          chromeMediaSource: 'desktop',
          chromeMediaSourceId: sourceId,
          minWidth: 1920,
          maxWidth: 1920,
          minHeight: 1080,
          maxHeight: 1080
        }
      }
    })

    /*
    stream
		.then(Mediastream => {
			let audioTracks = navigator.mediaDevices
				.getUserMedia({
					audio: true,
					video: false
				})
				.then(mediaStream =>{
					//mediaStream.getAudioTracks()[0];
					Mediastream.addTrack(mediaStream.getAudioTracks()[0]);
					//createRecorder(Mediastream); // createRecorder() 函数实现见下文
				});
		})
		.catch(err => console.error('startRecord error', err));
    */

    handleStream(stream)

    // create the media recorder
    //const options = { mimeType : 'video/webm; codecs=vp9'};
    const options = { mimeType : webmMimeType};
    mediaRecorder =  new MediaRecorder(stream, options);

    mediaRecorder.ondataavailable = handleDataAvailable;
    mediaRecorder.onstop = handleStop;
    
    
  } catch (e) {
    handleError(e)
  }
})

let recStarted = false;
let recTimer = false;

ipcRenderer.on('startRec', (event, sourceId) => {
  //console.log('ipc startRec');
  mediaRecorder.start();
  startBtn.classList.add('is-danger');
  startBtn.innerText = 'Recording';
});

ipcRenderer.on('stopRec', (event, sourceId) => {
  //console.log('ipc stopRec');
  mediaRecorder.stop();
  startBtn.classList.remove('is-danger');
  startBtn.innerText = 'Start';
});



ipcRenderer.on('startTimer', async (event, sourceId) => {


  try {

    recTimer = true;
    if (recStarted) {
      /*
      recordedChunks.forEach(function(b) {
          blobs2.push(b);
      });
      recordedChunks.length = 0;
      */
      mediaRecorder.stop();
      startBtn.classList.remove('is-danger');
      startBtn.innerText = 'Start';
      return;
    } else {
      //console.log('ipc startTimer');
      startBtn.classList.add('is-danger');
      startBtn.innerText = 'Recording';
      recStarted = true;
      const stream = await navigator.mediaDevices.getUserMedia({
        audio: micEnable,
        video: {
          mandatory: {
            chromeMediaSource: 'desktop',
            chromeMediaSourceId: sourceId,
            minWidth: 1920,
            maxWidth: 1920,
            minHeight: 1080,
            maxHeight: 1080
          }
        }
      })

      handleStream(stream)

      // create the media recorder
      //const options = { mimeType : 'video/webm; codecs=vp9'};
      const options = { mimeType : webmMimeType};
      mediaRecorder =  new MediaRecorder(stream, options);

      mediaRecorder.ondataavailable = handleDataAvailable;
      mediaRecorder.onstop = handleStop;
    
      //console.log('ipc startTimer');
      mediaRecorder.start(1000);
      startTime = Date.now();
      startBtn.classList.add('is-danger');
      startBtn.innerText = 'Recording';
      recStarted = true;

    }
    /*
    console.log('ipc startTimer');
    mediaRecorder.start(1000);
    startBtn.classList.add('is-danger');
    startBtn.innerText = 'Recording';
    recStarted = true;
    */
    
  } catch (e) {
    handleError(e)
  }
});

ipcRenderer.on('startTimer2', (event, sourceId) => {
  recTimer = true;
  if (recStarted) {
    mediaRecorder.stop();
    startBtn.classList.remove('is-danger');
    startBtn.innerText = 'Start';
    return;
  }
  //console.log('ipc startTimer');
  mediaRecorder.start();
  startBtn.classList.add('is-danger');
  startBtn.innerText = 'Recording';
  recStarted = true;
});

ipcRenderer.on('stopAll', (event, sourceId) => {
  //console.log('ipc stopAll');
  mediaRecorder.stop();
  startBtn.classList.remove('is-danger');
  startBtn.innerText = 'Start';
});

function handleStream (stream) {
  const video = document.querySelector('video')
  video.srcObject = stream
  video.onloadedmetadata = (e) => video.play()
}

function handleError (e) {
  console.log(e)
}


async function getVideoSources () {
desktopCapturer.getSources({ types: ['window', 'screen'] }).then(async sources => {
  for (const source of sources) {
    if (source.name === 'Hello World') {
      mainWindow.webContents.send('SET_SOURCE', source.id)
      return
    }
  }
})
}

//const videoElement = document.querySelector('video');
//const startBtn = document.getElementById('startBtn');
//const stopBtn = document.getElementById('stopBtn');

startBtn.onclick = e => {
  mediaRecorder.start();
  startBtn.classList.add('is-danger');
  startBtn.innerText = 'Recording';
};

stopBtn.onclick = e => {
  mediaRecorder.stop();
  startBtn.classList.remove('is-danger');
  startBtn.innerText = 'Start';
};

let mediaRecorder;
let recordedChunks = [];
let blobs2 = [];

let startTime;

function handleDataAvailable(e){
    //console.log('video data available');
    recordedChunks.push(e.data);
}

const {writeFile} = require('fs');

async function handleStop(e) {
  var duration = Date.now() - startTime;
  //var fixedWebMBlob = new Blob(recordedChunks, { type: 'video/webm' });
  var fixedWebMBlob = new Blob(recordedChunks, { type: webmMimeType });

  // v1: callback-style
  fixWebmDuration(fixedWebMBlob, duration, async function(fixedBlob) {
    //displayResult(fixedBlob);
    const buffer = Buffer.from(await fixedBlob.arrayBuffer());

    const date = new Date();
    //const formattedDate = moment(date).format('YYYY-MM-DD HH:mm:ss');
    const formattedDate = moment(date).format('YYYY-MM-DD-HH-mm-ss');
    //console.log(formattedDate); // 输出类似 '2021-05-14 16:30:00' 的字符串
    
    //let filePath = `vid-${Date.now()}.webm`;
    let filePath = `video/vid-${formattedDate}.webm`;

    if (filePath) {
      writeFile(filePath, buffer, () => console.log('video saved successfully!'));
    }
    //recordedChunks = []
    recordedChunks.length = 0;
    if (recTimer) {
      recStarted = true;
      mediaRecorder.start(1000);
      startTime = Date.now();
      startBtn.classList.add('is-danger');
      startBtn.innerText = 'Recording';
    }
  });

  /*
  // v2: promise-style, disable logging
  ysFixWebmDuration(fixedWebMBlob, duration, {logger: false})
      .then(function(fixedBlob) {
          //displayResult(fixedBlob);
      });
      */
}

async function handleStop0(e){

  console.log('handleStop');

  //const fixedWebMBlob = await fixWebmMetaInfo(new Blob([...recordedChunks], { type: webmMimeType }));
  const fixedWebMBlob = await fixWebmMetaInfo(new Blob([...recordedChunks], { type: webmMimeType }));

  /*
  const fixedWebMBlob = new Blob(recordedChunks, {
    type: webmMimeType
  });
  */
  
  const buffer = Buffer.from(await fixedWebMBlob.arrayBuffer());

  const date = new Date();
  //const formattedDate = moment(date).format('YYYY-MM-DD HH:mm:ss');
  const formattedDate = moment(date).format('YYYY-MM-DD-HH-mm-ss');
  //console.log(formattedDate); // 输出类似 '2021-05-14 16:30:00' 的字符串
  
  //let filePath = `vid-${Date.now()}.webm`;
  let filePath = `video/vid-${formattedDate}.webm`;

  if (filePath) {
    writeFile(filePath, buffer, () => console.log('video saved successfully!'));
  }
  //recordedChunks = []
  recordedChunks.length = 0;
  if (recTimer) {
    recStarted = true;
    startTime = Date.now();
    mediaRecorder.start(1000);
    startBtn.classList.add('is-danger');
    startBtn.innerText = 'Recording';
  }
}

async function handleStop1(e){
  //console.log('handleStop');
  const blob = new Blob(recordedChunks, {
      type: webmMimeType
    });
  
  const buffer = Buffer.from(await blob.arrayBuffer());

  const date = new Date();
  //const formattedDate = moment(date).format('YYYY-MM-DD HH:mm:ss');
  const formattedDate = moment(date).format('YYYY-MM-DD-HH-mm-ss');
  //console.log(formattedDate); // 输出类似 '2021-05-14 16:30:00' 的字符串
  
  //let filePath = `vid-${Date.now()}.webm`;
  let filePath = `video/vid-${formattedDate}.webm`;

  if (filePath) {
    writeFile(filePath, buffer, () => console.log('video saved successfully!'));
  }
  //recordedChunks = []
  recordedChunks.length = 0;
  if (recTimer) {
    recStarted = true;
    mediaRecorder.start(1000);
    startBtn.classList.add('is-danger');
    startBtn.innerText = 'Recording';
  }
}

async function handleStop2(e){

  console.log('handleStop');
  const blob = new Blob(blobs2, {
      type: webmMimeType
    });
  
  const buffer = Buffer.from(await blob.arrayBuffer());

  const date = new Date();
  //const formattedDate = moment(date).format('YYYY-MM-DD HH:mm:ss');
  const formattedDate = moment(date).format('YYYY-MM-DD-HH-mm-ss');
  //console.log(formattedDate); // 输出类似 '2021-05-14 16:30:00' 的字符串
  
  //let filePath = `vid-${Date.now()}.webm`;
  let filePath = `vid-${formattedDate}.webm`;

  if (filePath) {
    writeFile(filePath, buffer, () => console.log('video saved successfully!'));
  }
  //recordedChunks = []
  blobs2.length = 0;
  if (recTimer) {
    recStarted = true;
    mediaRecorder.start(1000);
    startBtn.classList.add('is-danger');
    startBtn.innerText = 'Recording';
  }
}


/*
const createHttpServer = async () => {
  var http = require('http');

  var server = http.createServer(function(req, res){
      //console.log('客户端请求url：' + req.url);
      //console.log('http版本：' + req.httpVersion);
      //console.log('http请求方法：' + req.method);
      //console.log('............');

      if (req.url == "/startRec") {mediaRecorder.start();
        startBtn.classList.add('is-danger');
        startBtn.innerText = 'Recording';
        //console.log('客户端请求url：' + req.url);
      }

      if (req.url == "/stopRec") {
        mediaRecorder.stop();
        startBtn.classList.remove('is-danger');
        startBtn.innerText = 'Start';
        //console.log('客户端请求url：' + req.url);
      }

      res.end('ok');
  });

  server.listen(4443);
}

//createHttpServer();
createHttpServer();
*/

